﻿using System;
using System.Runtime.InteropServices;
using UnityEngine;

namespace Recast
{
    public class NavMeshQuery : MonoBehaviour
    {
        IntPtr handle = IntPtr.Zero;

        private void Awake()
        {
            handle = NavMeshInterface.AllocNavMeshQuery();
        }

        public bool Valid
        {
            get
            {
                return handle != IntPtr.Zero;
            }
        }

        public bool InitNavMeshQuery(IntPtr mesh, int maxNodes = 2048)
        {
            if (handle == IntPtr.Zero || mesh == IntPtr.Zero)
                return false;
            return NavMeshInterface.InitNavMeshQuery(handle, mesh, maxNodes);
        }

        public uint FindNearestPoly(float[] center, float[] halfExtents,
                IntPtr filter,
                out uint nearestRef,float[] nearestPt)
        {
            if (handle == IntPtr.Zero || filter == IntPtr.Zero)
            {
                nearestRef = 0;
                return Recast.Status.DT_FAILURE | Recast.Status.DT_INVALID_PARAM;
            }
            return NavMeshInterface.FindNearestPoly(handle, center, halfExtents, filter, out nearestRef,nearestPt);
        }

        private void OnDestroy()
        {
            if (handle != IntPtr.Zero)
            {
                NavMeshInterface.FreeNavMeshQuery(handle);
                handle = IntPtr.Zero;
            }
        }
    }
}